﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.XPath;
using System.Xml;

namespace RuleXSoft.BizRuleCreator
{
    public partial class frmRulXAdminDialog : Form
    {
        bool newRowNeeded;
        int iClickedRowIndex;
        private DataGridViewCell clickedCell;
        public event EventHandler OnDocumentChanged;
        public bool IsNewRowValidated { get; set; }
        public string RulXFile { get; set; }

        private Dictionary<string, string> objRulXFieldList = null;
        private Dictionary<string, Dictionary<string, string>> objRuleXFieldList = null;

        public RulXActionEnum Action { get; set; }

        public Dictionary<string, Dictionary<string, string>> NewRuleXFieldValueList
        {
            get { return objRuleXFieldList; }
            set { objRuleXFieldList = value; }
        }

        public string KeyFieldName { get; set; }
        public string FieldUpdatedValue { get; set; }
        public string FieldOldValue { get; set; }
        public string RuleID { get; set; }

        public int NewAddedRowIndex { get; set; }
        public int NewAddedRowIndexOnPaste { get; set; }
        public string NewRuleID { get; set; }
        public int ClickedRowIndex { get; set; }
        public int RulXPasteRowIndex { get; set; }

        RulXAttributeObject objRulXAtt = null;
        Dictionary<string, RulXAttributeObject> objRulXAttributeList = null;
        List<RulXAttributeObject> objRuleXAttributeList = null;

        public Dictionary<string, RulXAttributeObject> RulXAttributeList
        {
            get { return objRulXAttributeList; }
            set { objRulXAttributeList = value; }
        }

        public List<RulXAttributeObject> RuleXAttributeList
        {
            get { return objRuleXAttributeList; }
            set { objRuleXAttributeList = value; }
        }

        public frmRulXAdminDialog()
        {
            InitializeComponent();
        }

        private IList<string> ExecuteRulXFileDialog()
        {
            IList<string> listRulXFileName = new List<string>();
            try
            {
                string strRulXFileName = string.Empty;
                

                dlgOpenFile.Filter = "RulX File(*.rulx)|*.rulx";
                dlgOpenFile.ShowDialog();
                dlgOpenFile.Multiselect = true;
                listRulXFileName = dlgOpenFile.FileNames;

                
                
            }
            catch (ArgumentOutOfRangeException ex)
            {
                
                MessageBox.Show("You must select an RulX file");

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

            return listRulXFileName;
        }


        public void PopulateTree(string dir, TreeNode node)
        {
            // get the information of the directory
            DirectoryInfo directory = new DirectoryInfo(dir);
            // loop through each subdirectory
            foreach (DirectoryInfo d in directory.GetDirectories())
            {
                // create a new node
                TreeNode t = new TreeNode(d.Name);
                // populate the new node recursively
                PopulateTree(d.FullName, t);
                node.Nodes.Add(t); // add the node to the "master" node
            }
            // lastly, loop through each file in the directory, and add these as nodes
            foreach (FileInfo f in directory.GetFiles())
            {
                // create a new node
                TreeNode t = new TreeNode(f.Name);
                // add it to the "master"
                node.Nodes.Add(t);
            }
        }

        private void ListDirectory(TreeView treeView, string path) 
        { 
            treeView.Nodes.Clear(); 
            var rootDirectoryInfo = new DirectoryInfo(path); 
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
            treeView.ExpandAll();
            this.lblRulXPath.Text = path;
        }

        private void PrepareRulXInfoPanel()
        {
            ScrollBar vScrollBar1 = new VScrollBar(); 
            vScrollBar1.Dock = DockStyle.Right; 
            vScrollBar1.Scroll += (sender, e) => { panelRulXInfo.VerticalScroll.Value = vScrollBar1.Value; }; 
            panelRulXInfo.Controls.Add(vScrollBar1);


        }

        private void PopulateRulXInfo(string sRulXFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(sRulXFile);
            XPathNavigator editor;

            editor = doc.CreateNavigator().SelectSingleNode("/Types/RuleSetName");

            XmlNode ruleXNameNode = ((System.Xml.IHasXmlNode)editor).GetNode();
            XmlAttribute attr = ruleXNameNode.Attributes["text"];
            this.txtRulXName.Text = attr.Value;

            editor = doc.CreateNavigator().SelectSingleNode("/Types/RuleSetDescription");

            XmlNode ruleXDescNode = ((System.Xml.IHasXmlNode)editor).GetNode();
            XmlAttribute attr1 = ruleXDescNode.Attributes["text"];
            this.txtRulXDesc.Text = attr1.Value;
        }
        
        private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo) 
        { 
            var directoryNode = new TreeNode(directoryInfo.Name); 
            foreach (var directory in directoryInfo.GetDirectories())         
                directoryNode.Nodes.Add(CreateDirectoryNode(directory));
            foreach (var file in directoryInfo.GetFiles())
            {
                if (file.Name.EndsWith(".rulx"))
                {
                    directoryNode.Nodes.Add(new TreeNode(file.Name));  
                }
            }
                
            return directoryNode; 
        } 

        private void lblLinkShowRulXFileDialog_Click(object sender, EventArgs e)
        {
            IList<string> listRulXFiles;
            listRulXFiles = ExecuteRulXFileDialog();

            this.tvRulXFileList.ShowRootLines = true;

            foreach (string item in listRulXFiles)
            {
                //PopulateTree(Path.GetDirectoryName(item), new TreeNode(item));
                ListDirectory(this.tvRulXFileList, Path.GetDirectoryName(item));
            }
        }

        private void frmRulXAdminDialog_Load(object sender, EventArgs e)
        {
            //this.tvRulXFileList.Nodes.Add("RulXRoot");
            objRulXAttributeList = new Dictionary<string, RulXAttributeObject>();
            objRuleXAttributeList = new List<RulXAttributeObject>();
            this.dgvRulesetManagement.DataError += new DataGridViewDataErrorEventHandler(dgvRulesetManagement_DataError);
            this.dgvRulesetManagement.NewRowNeeded += new DataGridViewRowEventHandler(this.dgvRulesetManagement_NewRowNeeded);

            NewAddedRowIndex = -1;
            ClickedRowIndex = -1;
            IsNewRowValidated = true;

            //rulXGridView.Width = this.Width;
            InitializeContextMenu();

            this.dgvRulesetManagement.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
            //this.rulXGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            objRuleXFieldList = new Dictionary<string, Dictionary<string, string>>();

            this.toolStripButtonDelRule.Enabled = false;
            PrepareRulXInfoPanel();
            iClickedRowIndex = 0;
            this.lblLnkAddOrCondition.Enabled = false;
        }

        void dgvRulesetManagement_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void InitializeContextMenu()
        {
            // Create the menu item.
            ToolStripMenuItem ctxMenuCut = new ToolStripMenuItem("Cut", null,
                new System.EventHandler(ShortcutMenuClickCut));
            ToolStripMenuItem ctxMenuCopy = new ToolStripMenuItem("Copy", null,
                new System.EventHandler(ShortcutMenuClickCopy));
            ToolStripMenuItem ctxMenuPaste = new ToolStripMenuItem("Paste", null,
                new System.EventHandler(ShortcutMenuClickPaste));
            //ToolStripMenuItem ctxMenuDelete = new ToolStripMenuItem("Delete", null,
            //    new System.EventHandler(ShortcutMenuClickDelete));
            ToolStripMenuItem ctxMenuRemoveRow = new ToolStripMenuItem("Remove Row", null,
                new System.EventHandler(ShortcutMenuClickRemoveRow));

            // Add the menu item to the shortcut menu.
            ContextMenuStrip ctxDashboardMenu = new ContextMenuStrip();
            ctxDashboardMenu.Items.Add(ctxMenuCut);
            ctxDashboardMenu.Items.Add(ctxMenuCopy);
            ctxDashboardMenu.Items.Add(ctxMenuPaste);
            //ctxDashboardMenu.Items.Add(ctxMenuDelete);
            ctxDashboardMenu.Items.Add(ctxMenuRemoveRow);

            this.dgvRulesetManagement.ContextMenuStrip = ctxDashboardMenu;
            this.dgvRulesetManagement.MouseDown += new MouseEventHandler(this.dgvRulesetManagement_MouseDown);
        }

        private void ShortcutMenuClickCut(object sender, System.EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void ShortcutMenuClickCopy(object sender, System.EventArgs e)
        {
            try
            {
                if (this.dgvRulesetManagement.GetCellCount(DataGridViewElementStates.Selected) > 0)
                {
                    Clipboard.SetDataObject(this.dgvRulesetManagement.GetClipboardContent());

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void ShortcutMenuClickPaste(object sender, System.EventArgs e)
        {
            try
            {
                PasteRulXRow();

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void PasteRulXRow()
        {
            //MessageBox.Show(Clipboard.GetText());
            IList<string> objdataList = Clipboard.GetText().Split('\t');

            int index = this.dgvRulesetManagement.SelectedRows[0].Index;
            RulXPasteRowIndex = index;
            NewAddedRowIndexOnPaste = index;
            //heck if the row already has ruleID in place
            if (this.dgvRulesetManagement.Rows[index].Cells[0].Value != null)
            {
                string strRuleID = this.dgvRulesetManagement.Rows[index].Cells[0].Value.ToString();
                //rulXGridView.Rows.RemoveAt(rulXGridView.Rows.Count - 1);
            }
            else
            {
                int nextRowID = 0;

                nextRowID = Convert.ToInt32(this.dgvRulesetManagement.Rows[this.dgvRulesetManagement.Rows.Count - 2].Cells["RuleID"].Value);

                nextRowID++;
                this.dgvRulesetManagement.Rows.Add();
                this.dgvRulesetManagement.Rows[index].Cells["RuleID"].Value = nextRowID.ToString();
                NewRuleID = nextRowID.ToString();
                this.dgvRulesetManagement.Rows[this.dgvRulesetManagement.Rows.Count - 3].Cells["RuleID"].Value = (nextRowID - 1).ToString();

            }

            objRuleXAttributeList.Clear();

            foreach (DataGridViewColumn col in this.dgvRulesetManagement.Columns)
            {
                if (!col.HeaderText.ToUpper().Trim().Equals("RULEID"))
                {
                    if (RulXPasteRowIndex != dgvRulesetManagement.Rows.Count - 2)
                    {
                        objRulXAtt = new RulXAttributeObject();
                        objRulXAtt.KeyFieldOldValue = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells[col.Index].Value.ToString();
                        objRulXAtt.KeyField = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells[col.Index].OwningColumn.HeaderText;
                        objRulXAtt.RuleID = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells["RuleID"].Value.ToString();


                        dgvRulesetManagement.Rows[index].Cells[col.Index].Value = objdataList[col.Index];

                        objRulXAtt.KeyFieldNewValue = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells[col.Index].Value.ToString();

                        objRuleXAttributeList.Add(objRulXAtt);
                    }
                    else
                    {
                        dgvRulesetManagement.Rows[index].Cells[col.Index].Value = objdataList[col.Index];
                    }
                }
            }

            if (RulXPasteRowIndex != this.dgvRulesetManagement.Rows.Count - 2)
            {
                Action = RulXActionEnum.RULXEDIT;
            }
            else
            {
                Action = RulXActionEnum.RULXADD;
                SetRuleXFieldList(NewAddedRowIndexOnPaste);
            }

            this.dgvRulesetManagement.CurrentCell = this.dgvRulesetManagement.Rows[index].Cells[this.dgvRulesetManagement.Columns.Count - 1];
            this.dgvRulesetManagement.BeginEdit(true);
        }

        private void SetRuleXFieldList(int rowIndex)
        {
            try
            {
                objRulXFieldList = new Dictionary<string, string>();
                //objRuleXFieldList = new Dictionary<string, Dictionary<string,string>>();
                //objRulXFieldList.Clear();

                string strDataType = string.Empty;
                string strDataOutput = string.Empty;
                string strFieldValue = string.Empty;
                string strDataTypeAndOuputTypeVal = string.Empty;

                if (objRuleXFieldList.ContainsKey(NewRuleID))
                {
                    return;
                }


                foreach (DataGridViewColumn dgvc in dgvRulesetManagement.Columns)
                {

                    if (!dgvc.HeaderText.ToUpper().Trim().Equals("RULEID"))
                    {
                        strDataTypeAndOuputTypeVal = dgvRulesetManagement.Rows[0].Cells[dgvc.HeaderText.Trim()].Value.ToString();
                        IList<string> objList = strDataTypeAndOuputTypeVal.Split(' ');

                        strDataType = objList[0];
                        strDataOutput = objList[1].Substring(1, objList[1].Length - 2);


                        if (dgvRulesetManagement.Rows[rowIndex].Cells[dgvc.HeaderText.Trim()].Value != null)
                        {
                            strFieldValue = dgvRulesetManagement.Rows[rowIndex].Cells[dgvc.HeaderText.Trim()].Value.ToString();
                        }
                        //strDataType = DataGridViewControl.Rows[0].Cells[dgvc.HeaderText.Trim()].Value.ToString();

                        objRulXFieldList.Add(dgvc.HeaderText.Trim(), strFieldValue + "|" + strDataType + "|" + strDataOutput);
                        //DataGridViewControl.Rows[NewAddedRowIndex].Cells[dgvc.HeaderText.Trim()].Value.ToString()

                    }
                }
                //objRuleXFieldList.Clear();
                objRuleXFieldList.Add(NewRuleID, objRulXFieldList);


            }
            catch (ArgumentNullException argNullEx)
            {

                throw argNullEx;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private void SetRulXAttributeOnPaste(List<RulXAttributeObject> objRulXRowValueList)
        {
            objRuleXAttributeList.Clear();

            foreach (DataGridViewColumn col in this.dgvRulesetManagement.Columns)
            {
                objRulXAtt = new RulXAttributeObject();
                FieldUpdatedValue = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells[col.Index].Value.ToString();
                KeyFieldName = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells[col.Index].OwningColumn.HeaderText;
                RuleID = dgvRulesetManagement.Rows[RulXPasteRowIndex].Cells["RuleID"].Value.ToString();

                objRulXAtt.KeyField = KeyFieldName;
                objRulXAtt.KeyFieldNewValue = FieldUpdatedValue;
                objRulXAtt.RuleID = RuleID;

                objRuleXAttributeList.Add(objRulXAtt);
            }
        }

        private void ShortcutMenuClickDelete(object sender, System.EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        public event EventHandler OnRulXRowRemoved;

        private void ShortcutMenuClickRemoveRow(object sender, System.EventArgs e)
        {
            try
            {
                RemoveRulXRow(this.RulXFile);
                ReCalculateRuleIDSequence();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void RemoveRulXRow(string RulXFile)
        {
            XMLRecordGenerator objXmlRecGen = new XMLRecordGenerator();

            string strRuleID = string.Empty;
            List<string> ruleIDList = new List<string>();
            //Get the selected rule ID
            //string strRuleID = rulXGridView.SelectedRows[0].Cells["RuleID"].Value.ToString();
            DataGridViewSelectedRowCollection dgvrCollection = this.dgvRulesetManagement.SelectedRows;

            if (MessageBox.Show("Are you sure you want to Remove the selected Rule/s?", "Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                if (dgvrCollection != null && dgvrCollection.Count > 0)
                {

                    foreach (DataGridViewRow dgvr in dgvrCollection)
                    {
                        strRuleID = dgvr.Cells["RuleID"].Value.ToString();
                        ruleIDList.Add(strRuleID);
                        this.dgvRulesetManagement.Rows.RemoveAt(dgvr.Index);
                    }

                    objXmlRecGen.RemoveRulXData(RulXFile, ruleIDList);


                    this.toolStripButtonDelRule.Enabled = false;
                    
                }
                else
                {
                    if (ClickedRowIndex != 0 && ClickedRowIndex != -1)
                    {
                        strRuleID = this.dgvRulesetManagement.Rows[ClickedRowIndex].Cells["RuleID"].Value.ToString();
                        ruleIDList.Add(strRuleID);
                    }
                    objXmlRecGen.RemoveRulXData(RulXFile, ruleIDList);
                    this.dgvRulesetManagement.Rows.RemoveAt(ClickedRowIndex);
                }
            }
            else
            {
                return;
            }

            if (OnRulXRowRemoved != null)
            {
                OnRulXRowRemoved(this, EventArgs.Empty);
            }
        }

        private void toolStripButton1_MouseHover(object sender, EventArgs e)
        {
            //toolStripButton1.BackColor = System.Drawing.Color.Orange;
        }
        private void toolStripButton2_MouseHover(object sender, EventArgs e)
        {
            //toolStripButton2.BackColor = System.Drawing.Color.Orange;
        }

        private void tvRulXFileList_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                string sRulXFile = string.Empty;
                var rootNode = FindRootNode(e.Node); 
                if (e.Node != rootNode)
                {
                    sRulXFile = this.lblRulXPath.Text + @"\" + e.Node.Text; 
                }

                RefreshRulXGrid(sRulXFile);
                this.RulXFile = sRulXFile;
                PopulateRulXInfo(RulXFile);
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private TreeNode FindRootNode(TreeNode treeNode) 
        { 
            while (treeNode.Parent != null) 
            { 
                treeNode = treeNode.Parent; 
            } 
            return treeNode; 
        } 

        private static XPathNodeIterator GetXMLNodes(string fileName)
        {
            XPathNodeIterator _xmlNodes;

            XPathDocument document = new XPathDocument(fileName);
            XPathNavigator navigator = document.CreateNavigator();
            XPathNodeIterator nodes = navigator.Select("Types/RuleSetClass/RuleSet/Rule");

            _xmlNodes = nodes;

            return _xmlNodes;
        }

        private DataTable GetDataTableFromSelectedRulX(string sRulXFile)
        {
            DataTable dtXmlRec = new DataTable();
            try
            {
                XMLRecordGenerator objXMLRecGen = new XMLRecordGenerator();

                dtXmlRec = objXMLRecGen.GenerateData(objXMLRecGen.GetXMLNodes(sRulXFile));

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            return dtXmlRec;

        }

        private void RefreshRulXGrid(string sRulXFile)
        {
            try
            {
                //editorControl.DataGridViewControl.DataSource = GetDatatable();
                //string[] strfieldValArray;
                DataTable dtRulX = new DataTable();
                dtRulX = GetDataTableFromSelectedRulX(sRulXFile);
                this.dgvRulesetManagement.Rows.Clear();
                this.dgvRulesetManagement.Columns.Clear();
                if (dtRulX != null)
                {
                    foreach (DataColumn col in dtRulX.Columns)
                    {
                        this.dgvRulesetManagement.Columns.Add(col.Caption, col.Caption);
                    }

                    foreach (DataRow row in dtRulX.Rows)
                    {
                        this.dgvRulesetManagement.Rows.Add(row.ItemArray);
                    }
                }

                //editorControl.DataGridViewControl.DataSource = GetDatatable();
                this.dgvRulesetManagement.Columns["RuleID"].ReadOnly = true;
                this.dgvRulesetManagement.Columns["RuleID"].CellTemplate.Style.ForeColor = System.Drawing.Color.Gray;

                this.dgvRulesetManagement.Rows[0].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                this.dgvRulesetManagement.Rows[0].DefaultCellStyle.Font = new Font("Vardana", 8, FontStyle.Italic);
                this.dgvRulesetManagement.Rows[0].ReadOnly = true;
                this.dgvRulesetManagement.Rows[0].Cells[0].Selected = false;
                this.dgvRulesetManagement.Rows[0].Frozen = true;
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private void dgvRulesetManagement_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            ClickedRowIndex = e.RowIndex;
        }

        private void dgvRulesetManagement_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                objRulXAtt = new RulXAttributeObject();
                if (dgvRulesetManagement.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                {

                    FieldOldValue = dgvRulesetManagement.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    objRulXAtt.KeyFieldOldValue = FieldOldValue;
                }

            }

            catch (System.Data.ReadOnlyException readOnlyEx)
            {

                MessageBox.Show(readOnlyEx.Message);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message); ;
            }
        }
        
        private void dgvRulesetManagement_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvRulesetManagement.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
            {
                FieldUpdatedValue = dgvRulesetManagement.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                KeyFieldName = dgvRulesetManagement.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.HeaderText;
                RuleID = dgvRulesetManagement.Rows[e.RowIndex].Cells["RuleID"].Value.ToString();



                objRulXAtt.KeyField = KeyFieldName;
                objRulXAtt.KeyFieldNewValue = FieldUpdatedValue;
                objRulXAtt.RuleID = RuleID;

                objRuleXAttributeList.Add(objRulXAtt);
            }


            if (OnDocumentChanged != null)
            {
                OnDocumentChanged(this, EventArgs.Empty);
            }
        }

        private void dgvRulesetManagement_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            ClickedRowIndex = e.RowIndex;
        }

        private void dgvRulesetManagement_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (this.dgvRulesetManagement != null)
            {
                Point point1 = this.dgvRulesetManagement.CurrentCellAddress;
                if (point1.X == e.ColumnIndex &&
                    point1.Y == e.RowIndex &&
                    e.Button == MouseButtons.Left &&
                    this.dgvRulesetManagement.EditMode !=
                    DataGridViewEditMode.EditProgrammatically)
                {
                    this.dgvRulesetManagement.BeginEdit(true);
                }
            }
        }

        private void dgvRulesetManagement_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            dgvRulesetManagement.Rows[e.RowIndex].ErrorText = "";
            int newInteger;

            // Don't try to validate the 'new row' until finished 
            // editing since there
            // is not any point in validating its initial value.
            if (dgvRulesetManagement.Rows[e.RowIndex].IsNewRow) { return; }
            //if (e.FormattedValue.ToString().Length == 0)
            //{
            //    e.Cancel = true;
            //    rulXGridView.Rows[e.RowIndex].ErrorText = "Please enter the required value";
            //    //rulXGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Please enter the required value";

            //}
            //else
            //{
            //    //if((!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0))
            //    //{

            //    //}
            //    e.Cancel = false;
            //}

            string strDataType = dgvRulesetManagement.Rows[0].Cells[e.ColumnIndex].Value.ToString();

            if (e.ColumnIndex != 0)
            {
                if (!string.IsNullOrEmpty(strDataType))
                {
                    if (strDataType.Trim().ToUpper().StartsWith("STRING") && IsNumeric(e.FormattedValue.ToString()))
                    {
                        e.Cancel = true;
                        dgvRulesetManagement.Rows[e.RowIndex].ErrorText = "Please enter the text value";
                        //rulXGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Please enter the required value";

                    }
                    else if ((strDataType.Trim().ToUpper().StartsWith("INT") || strDataType.Trim().ToUpper().StartsWith("DOUBLE")) && !IsNumeric(e.FormattedValue.ToString()))
                    {
                        e.Cancel = true;
                        dgvRulesetManagement.Rows[e.RowIndex].ErrorText = "Please enter the numeric value";
                        //rulXGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Please enter the required value";

                    }
                    else if (strDataType.Trim().ToUpper().StartsWith("BOOLEAN") && !IsBoolean(e.FormattedValue.ToString()))
                    {
                        e.Cancel = true;
                        dgvRulesetManagement.Rows[e.RowIndex].ErrorText = "Please enter the boolean value";
                        //rulXGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Please enter the required value";

                    }
                    else
                    {
                        //if((!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0))
                        //{

                        //}
                        e.Cancel = false;
                    }
                } 
            }
        }

        private bool IsNumeric(string strVal)
        {
            // Return true if this is a number.
            int iNumber;
            double dNumber;
            return (int.TryParse(strVal, out iNumber) || double.TryParse(strVal, out dNumber));

        }

        private bool IsBoolean(string strVal)
        {
            // Return true if this is a number.
            bool bVal;

            return bool.TryParse(strVal, out bVal);

        }

        private void dgvRulesetManagement_Leave(object sender, EventArgs e)
        {
            if (!IsNewRowValidated)
            {
                MessageBox.Show("Please enter all required values before save", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
        private void dgvRulesetManagement_MouseDown(object sender, MouseEventArgs e)
        {
            // If the user right-clicks a cell, store it for use by the shortcut menu.
            if (e.Button == MouseButtons.Right)
            {
                if (dgvRulesetManagement.SelectedCells.Count > 0)
                {
                    clickedCell = dgvRulesetManagement.SelectedCells[0];
                }
                else
                {

                }
            }
            else
            {
                return;
            }
        }

        private void dgvRulesetManagement_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
        {
            newRowNeeded = true;
            //MessageBox.Show(GetRuleXFieldList()[0].ToString());
            //Storing newly added row index
            NewAddedRowIndex = e.Row.Index;
            //SetRuleXFieldList();

            //Action = RulXActionEnum.RULXADD;
        }

        private void dgvRulesetManagement_RowLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (NewAddedRowIndex == e.RowIndex)
                {
                    //Do the Row Addition logic
                    //set the RulX field list
                    SetRuleXFieldList(NewAddedRowIndex);

                }

                if (NewAddedRowIndex != -1 
                    && this.dgvRulesetManagement.Rows[e.RowIndex].HeaderCell.Value.ToString().Trim().ToUpper().Equals("OR"))
                {
                    Action = RulXActionEnum.RULXADD;
                }
                else
                {
                    Action = RulXActionEnum.RULXEDIT;
                }
            }
            catch (ArgumentNullException ex)
            {

                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dgvRulesetManagement_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            //Check if this row is intended to be a new row then essentially set the newrowindex value 
            //and subseqiently set the new ruleid value
            if (e.RowIndex == dgvRulesetManagement.Rows.Count - 1)
            {
                newRowNeeded = true;
                NewAddedRowIndex = e.RowIndex;

                this.toolStripButtonDelRule.Enabled = false;
            }
            else
            {
                if (e.RowIndex != 0)
                {
                    this.toolStripButtonDelRule.Enabled = true;
                }
                else
                {
                    this.toolStripButtonDelRule.Enabled = false;
                }
            }
        }

        private void dgvRulesetManagement_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                if (newRowNeeded)
                {
                    newRowNeeded = false;
                    dgvRulesetManagement.Rows[e.RowIndex - 1].Cells["RuleID"].Value = GetNewRuleID().ToString();
                    NewRuleID = GetNewRuleID().ToString();

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private int GetNewRuleID()
        {
            int nextRowID = 0;
            nextRowID = Convert.ToInt32(dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 3].Cells["RuleID"].Value);
            nextRowID++;
            return nextRowID;
        }

        private void dgvRulesetManagement_RowValidated(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvRulesetManagement_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                DataGridViewRow row = dgvRulesetManagement.Rows[e.RowIndex];

                // Don't try to validate the 'new row' until finished 
                // editing since there
                // is not any point in validating its initial value.
                if (dgvRulesetManagement.Rows[e.RowIndex].IsNewRow) { return; }

                //foreach (DataGridViewColumn colItem in rulXGridView.Columns)
                //{
                //    DataGridViewCell cell = row.Cells[colItem.HeaderText.Trim()];
                //    //if (cell.RowIndex <= NewAddedRowIndex)
                //    //{
                //    if (cell.Value.ToString().Length == 0
                //        || cell.Value == DBNull.Value)
                //    {
                //        cell.ErrorText = "Please enter " + colItem.HeaderText.Trim() + " value";
                //        rulXGridView.Rows[cell.RowIndex].ErrorText = "Please enter the required value";
                //        e.Cancel = true;
                //        //IsNewRowValidated = false;
                //    }
                //    else
                //    {
                //        cell.ErrorText = string.Empty;
                //        rulXGridView.Rows[cell.RowIndex].ErrorText = string.Empty;
                //        e.Cancel = false;
                //        //IsNewRowValidated = true;

                //    }
                //    //}
                //}
                //set the RulX field list
                //SetRuleXFieldList();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.dgvRulesetManagement.Rows.Insert(2);

        }

        private void SaveNewRulX(string rulXFileName)
        {
            try
            {
                string keyField = KeyFieldName;
                string newValue = FieldUpdatedValue;
                string oldValue = FieldOldValue;
                string ruleID = RuleID;

                //foreach (DataGridViewRow dgvr in editorControl.DataGridViewControl.Rows)
                //{
                XMLRecordGenerator objXmlRecGen = new XMLRecordGenerator();
                //objXmlRecGen.UpdateRulXData(rulXFileName, ruleID, keyField, newValue);
                //objXmlRecGen.UpdateRulXData2(rulXFileName, ruleID, keyField, oldValue, newValue);
                objXmlRecGen.GenerateNewRulXData(rulXFileName, NewRuleXFieldValueList);
                //}
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void SaveRulX(string rulXFileName)
        {
            try
            {
                string keyField = KeyFieldName;
                string newValue = FieldUpdatedValue;
                string oldValue = FieldOldValue;
                string ruleID = RuleID;

                foreach (DataGridViewRow dgvr in dgvRulesetManagement.Rows)
                {
                    if (dgvr.Cells[0].Value != null)
                    {
                        if (!dgvr.Cells[0].Value.ToString().ToUpper().Trim().Equals("RULEID"))
                        {
                            XMLRecordGenerator objXmlRecGen = new XMLRecordGenerator();
                            //objXmlRecGen.UpdateRulXData(rulXFileName, ruleID, keyField, newValue);
                            //objXmlRecGen.UpdateRulXData2(rulXFileName, ruleID, keyField, oldValue, newValue);
                            objXmlRecGen.UpdateRulXData3(rulXFileName, RuleXAttributeList);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void toolStripButtonAddRule_Click(object sender, EventArgs e)
        {
            try
            {
                int nextRowID = 0;

                newRowNeeded = true;
                int newRowIndex = dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 1].Index;

                NewAddedRowIndex = newRowIndex;
                //SetRuleXFieldList();

                nextRowID = Convert.ToInt32(dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 2].Cells["RuleID"].Value);

                nextRowID++;
                dgvRulesetManagement.Rows.Add();
                dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 2].Cells["RuleID"].Value = nextRowID.ToString();
                NewRuleID = nextRowID.ToString();
                dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 3].Cells["RuleID"].Value = (nextRowID - 1).ToString();

                dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 3].Selected = false;
                //DataGridViewControl.Rows[DataGridViewControl.Rows.Count - 2].Selected = true;
                dgvRulesetManagement.Rows[0].Cells[0].Selected = false;
                //DataGridViewControl.Rows[DataGridViewControl.Rows.Count - 2].Cells[1].ed
                dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 2].Cells[1].Value = "<Value>";
                dgvRulesetManagement.CurrentCell = dgvRulesetManagement.Rows[dgvRulesetManagement.Rows.Count - 2].Cells[1];
                this.dgvRulesetManagement.BeginEdit(true);

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void toolStripButtonDelRule_Click(object sender, EventArgs e)
        {
            RemoveRulXRow(this.RulXFile);
            ReCalculateRuleIDSequence();
        }

        private void toolStripButtonSaveRule_Click(object sender, EventArgs e)
        {
            if (Action == RulXActionEnum.RULXADD)
            {
                if (CheckIfRulXGridValidated())
                {
                    SaveNewRulX(this.RulXFile);
                }
                else
                {
                    MessageBox.Show("Please enter all required values before save", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                }
            }
            else
            {
                if (CheckIfRulXGridValidated())
                {
                    SaveRulX(this.RulXFile);
                }
                else
                {
                    MessageBox.Show("Please enter all required values before save", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                }
            }

            
        }

        public bool CheckIfRulXGridValidated()
        {
            bool isValidated = true;
            //replace this.dataGridView1 with the name of your datagridview control 
            foreach (DataGridViewRow row in this.dgvRulesetManagement.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.ErrorText.Length > 0)
                    {
                        isValidated = false;
                        break;
                    }
                }
                if (!isValidated)
                    break;
            }

            return isValidated;
        } 


        private void lblLnkAddOrCondition_Click(object sender, EventArgs e)
        {
            this.dgvRulesetManagement.Rows.Insert(iClickedRowIndex + 1);
            ReCalculateRuleIDSequence();
            Action = RulXActionEnum.RULXADD;

            this.dgvRulesetManagement.Rows[iClickedRowIndex + 1].HeaderCell.Value = "OR";
            int newRowIndex = iClickedRowIndex + 1;

            NewAddedRowIndex = newRowIndex;
        }

        private void dgvRulesetManagement_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            iClickedRowIndex = e.RowIndex;
            if (iClickedRowIndex > 0)
            {
                this.lblLnkAddOrCondition.Enabled = true;
            }
            else
            {
                this.lblLnkAddOrCondition.Enabled = false;
            }
        }

        private void ReCalculateRuleIDSequence()
        {
            int iRuleID = 0;
            foreach (DataGridViewRow dgvr in this.dgvRulesetManagement.Rows)
            {
                if (dgvr.Index != 0 && dgvr.Index != dgvRulesetManagement.Rows.Count - 1)
                {
                    dgvr.Cells[0].Value = Convert.ToString(iRuleID + 1);
                    iRuleID++; 
                }
            }
        }
    }


}
